package chapter1.XML.task;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.List;
import java.util.Scanner;

public class XMLSupermarket {
    public static void main(String[] args) throws DocumentException {
        Scanner input = new Scanner(System.in);
        int choice;
        while (true) {
            System.out.println("1：读取商品信息，2，查询商品，3：修改库存量，4：购买商品，5：添加商品，9：退出");
            System.out.print("请选择：");
            choice = input.nextInt();
            if (choice == 1) {
                read();
            } else if (choice == 2) {
                System.out.print("请输入要查找的商品编号：");
                searchByitemno(input.next());
            } else if (choice == 3) {
                System.out.print("请输入商品编号和要修改的库存量：");
                modifyProduct(input.next(), input.next());
            } else if (choice == 4) {
                System.out.print("请输入商品编号和要购买的数量：");
                buyProduct(input.next(), input.nextInt());
            } else if (choice == 5) {
                //(boolean b, String addr, String itemno, String name, double price, int stockcount, String unit) {
                System.out.print("请输入商品是否打折：");
                boolean b = input.nextBoolean();
                System.out.print("请输入商品的工厂地址：");
                String addr = input.next();
                System.out.print("请输入商品编号：");
                String itemno = input.next();
                System.out.print("请输入商品名称：");
                String name = input.next();
                System.out.print("请输入商品价格：");
                double price = input.nextDouble();
                System.out.print("请输入商品库存量：");
                int stockcount = input.nextInt();
                System.out.print("请输入商品计价单位：");
                String unit = input.next();
                addNewProduct(b, addr, itemno, name, price, stockcount, unit);
            } else if (choice == 9) {
                break;
            } else {
                System.out.println("输入错误");
                continue;
            }
        }

    }


    //读取
    public static void read() throws DocumentException {
        //构建一个阅读器
        SAXReader reader = new SAXReader();
        //获得Document对象
        Document document = reader.read(new File("F:\\java_workspace\\IdeaProjects\\java82\\java_advance\\src\\chapter1\\XML\\task\\products.xml"));
        Element root = document.getRootElement();
//        System.out.println(root.getName());
        System.out.println(root.attributeValue("name"));
        //》》》List elements = root.elements();//所有的子节点
        //从当前的根节点开始找
        List<Element> list = root.selectNodes("product");
        for (Element e : list) {
            //访问e的属性,都是字符串。。。
            String dicount = e.attributeValue("discount");
            if (Boolean.parseBoolean(dicount))
                dicount = "可打折";
            else
                dicount = "不可打折";
            String factoryaddr = e.attributeValue("factoryaddr");

            //Element ename = (Element) e.selectNodes("name").get(0);
            Element itemno = (Element) e.selectSingleNode("itemno");//查找唯一子节点
            String sitemno = itemno.getTextTrim();//!
            String name = ((Element) (e.selectSingleNode("name"))).getTextTrim();
            String price = ((Element) (e.selectSingleNode("price"))).getTextTrim();
            String stockcount = ((Element) (e.selectSingleNode("stockcount"))).getTextTrim();
            String unit = ((Element) (e.selectSingleNode("unit"))).getTextTrim();

            if (factoryaddr != null)
                System.out.printf("商品信息是：编号：%s，名称：%s，单价：%s元，库存量：%s%s，%s，工厂地址：%s\n", sitemno, name, price, stockcount, unit, dicount, factoryaddr);
            else
                System.out.printf("商品信息是：编号：%s，名称：%s，单价：%s元，库存量：%s%s，%s\n", sitemno, name, price, stockcount, unit, dicount);
        }
    }


    //根据商品编号itemno的值，查找商品信息
    public static void searchByitemno(String itemnoNum) throws DocumentException {
//构建一个阅读器
        SAXReader reader = new SAXReader();
        //获得Document对象
        Document document = reader.read(new File("F:\\java_workspace\\IdeaProjects\\java82\\java_advance\\src\\chapter1\\XML\\task\\products.xml"));

        List<Element> list = document.selectNodes("/shop/product[itemno='" + itemnoNum + "']");

        if (list.size() == 0) {
            System.out.println("没有这个itemno的商品信息");
            return;
        }
        System.out.println("查找的结果如下：");
        for (Element e : list) {
            //访问e的属性,都是字符串。。。
            String dicount = e.attributeValue("discount");
            if (Boolean.parseBoolean(dicount))
                dicount = "可打折";
            else
                dicount = "不可打折";
            String factoryaddr = e.attributeValue("factoryaddr");

            //Element ename = (Element) e.selectNodes("name").get(0);
            Element itemno = (Element) e.selectSingleNode("itemno");//查找唯一子节点
            String sitemno = itemno.getTextTrim();//!
            String name = ((Element) (e.selectSingleNode("name"))).getTextTrim();
            String price = ((Element) (e.selectSingleNode("price"))).getTextTrim();
            String stockcount = ((Element) (e.selectSingleNode("stockcount"))).getTextTrim();
            String unit = ((Element) (e.selectSingleNode("unit"))).getTextTrim();

            if (factoryaddr != null)
                System.out.printf("商品信息是：编号：%s，名称：%s，单价：%s元，库存量：%s%s，%s，工厂地址：%s\n", sitemno, name, price, stockcount, unit, dicount, factoryaddr);
            else
                System.out.printf("商品信息是：编号：%s，名称：%s，单价：%s元，库存量：%s%s，%s\n", sitemno, name, price, stockcount, unit, dicount);
        }
    }


    //根据商品编号itemno,修改商品的库存信息stockcount
    public static void modifyProduct(String itemnoNum, String stockcountNum) {
        SAXReader reader = new SAXReader();
        //获得Document对象
        try {
            Document document = reader.read(new File("F:\\java_workspace\\IdeaProjects\\java82\\java_advance\\src\\chapter1\\XML\\task\\products.xml"));
            Element product = (Element) document.selectSingleNode("/shop/product[itemno='" + itemnoNum + "']");
            if (product == null) {
                System.out.println("没有这个编号的商品");
                return;
            }
            product.selectSingleNode("stockcount").setText(stockcountNum);

            //写回到xml文件中
            //控制格式和字符集
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            XMLWriter xm = new XMLWriter(new FileOutputStream("F:\\java_workspace\\IdeaProjects\\java82\\java_advance\\src\\chapter1\\XML\\task\\products.xml"), format);
            xm.write(document);
            xm.close();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }


    //根据商品编号itemno,购买一定数量的商品
    public static void buyProduct(String itemnoNum, int number) {
        SAXReader reader = new SAXReader();
        //获得Document对象
        try {
            Document document = reader.read(new File("F:\\java_workspace\\IdeaProjects\\java82\\java_advance\\src\\chapter1\\XML\\task\\products.xml"));
            Element product = (Element) document.selectSingleNode("/shop/product[itemno='" + itemnoNum + "']");
            if (product == null) {
                System.out.println("没有这个编号的商品");
                return;
            }

            int a = Integer.parseInt(((Element) product.selectSingleNode("stockcount")).getTextTrim());
            if (a < number) {
                System.out.println("购买商品的数量超过总库存，购买失败");
                return;
            }
            double price = Double.parseDouble(((Element) product.selectSingleNode("price")).getTextTrim());
            if (Boolean.parseBoolean(product.attributeValue("discount")))
                System.out.println("顾客消费应付" + (price * number * 0.7) + "元");
            else
                System.out.println("顾客消费应付" + (price * number) + "元");

            product.selectSingleNode("stockcount").setText(String.valueOf(a - number));


            //写回到xml文件中
            //控制格式和字符集
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            XMLWriter xm = new XMLWriter(new FileOutputStream("F:\\java_workspace\\IdeaProjects\\java82\\java_advance\\src\\chapter1\\XML\\task\\products.xml"), format);
            xm.write(document);
            xm.close();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }


    //加新商品
    public static void addNewProduct(boolean b, String addr, String itemno, String name, double price, int stockcount, String unit) {
        SAXReader reader = new SAXReader();
        //获得Document对象
        try {
            Document document = reader.read(new File("F:\\java_workspace\\IdeaProjects\\java82\\java_advance\\src\\chapter1\\XML\\task\\products.xml"));
            Element root = document.getRootElement();
            List<Element> list = root.selectNodes("product");
            String itemno1, name1;
            for (Element e : list) {
                itemno1 = ((Element) (e.selectSingleNode("itemno"))).getTextTrim();
                name1 = ((Element) (e.selectSingleNode("name"))).getTextTrim();
                if (itemno1.equals(itemno) || name1.equals(name)) {
                    System.out.println("商品信息重复，不能添加");
                    return;
                }
            }

            //商品号和商品名称都不重复，新建一个product节点
            Element product = root.addElement("product");
            product.addAttribute("discount", String.valueOf(b));
            product.addAttribute("factoryaddr", addr);
            product.addElement("itemno").setText(itemno);
            product.addElement("name").setText(name);
            product.addElement("price").setText(String.valueOf(price));
            product.addElement("stockcount").setText(String.valueOf(stockcount));
            product.addElement("unit").setText(unit);
            System.out.println("添加新商品成功");

            //写回到xml文件中
            //控制格式和字符集
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            XMLWriter xm = new XMLWriter(new FileOutputStream("F:\\java_workspace\\IdeaProjects\\java82\\java_advance\\src\\chapter1\\XML\\task\\products.xml"), format);
            xm.write(document);
            xm.close();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }


}
